/**
 * 
 */
package any.radeox.filter;

import java.text.MessageFormat;

import org.radeox.api.engine.context.InitialRenderContext;
import org.radeox.filter.CacheFilter;
import org.radeox.filter.context.FilterContext;
import org.radeox.filter.regex.LocaleRegexTokenFilter;
import org.radeox.regex.MatchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import any.radeox.OutlineController;

/**
 * @author keke
 * @version $Revision: 21 $
 */
public class HeadingFilter extends LocaleRegexTokenFilter implements
        CacheFilter {
	private static final Logger	LOG	= LoggerFactory
	                                        .getLogger(HeadingFilter.class);
	protected MessageFormat	    formatter;

	public String handleMatch(final MatchResult result,
	        final FilterContext context) {
		final String headLevel = result.group(1);
		if (LOG.isDebugEnabled()) {
			LOG.debug("Heading number is {}", headLevel);
		}
		final String title = result.group(2);
		final OutlineController outlineController = (OutlineController) context
		        .getRenderContext().get(OutlineController.KEY);
		String headerName = null;
		final StringBuilder sb = new StringBuilder();
		if (outlineController != null) {
			headerName = outlineController.addHeader(headLevel, title);
			sb.append("<a name=\"").append(headerName).append("\">");
		}
		sb.append(formatHeader(headLevel, title, headerName));
		if (headerName != null) {
			sb.append("</a>");
		}
		return sb.toString();
	}

	@Override
	public void handleMatch(final StringBuffer buffer,
	        final MatchResult result, final FilterContext context) {
		buffer.append(handleMatch(result, context));
	}

	public void setInitialContext(final InitialRenderContext context) {
		super.setInitialContext(context);
		final String outputTemplate = outputMessages.getString(getLocaleKey()
		        + ".print");
		formatter = new MessageFormat("");
		formatter.applyPattern(outputTemplate);
	}

	protected String formatHeader(final String headLevel, final String title,
	        final String headerName) {
		return formatter.format(new Object[] { headLevel, title });
	}

	@Override
	protected String getLocaleKey() {
		return "filter.heading2";
	}
}
